﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public enum GameMode {
    Normal,
    Difficult
}

public class GameManager : MonoBehaviour {
    public GameMode gameMode = GameMode.Normal;
    public static GameManager Instance;
    public static CustomEvent onGameOver = EventFactory.CreatCustomEvent ();

    private PlayerController2D playerCtrl;
    public PlayerController2D PlayerCtrl {
        get {
            if (playerCtrl == null) {
                playerCtrl = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerController2D> ();
            }
            return playerCtrl;
        }
    }
    private void Awake () {
        if (GameManager.Instance != null) {
            Destroy (this.gameObject);
            return;
        }
        Instance = this;
        DontDestroyOnLoad (this.gameObject);
    }
    private void Update () {
        if (SceneManager.GetActiveScene ().name == "GameMain")
            return;
        if (Input.GetKeyDown (KeyCode.Escape)) {
            UIManager.Instance.contentListView.Show ();
        }
        if (playerCtrl!=null)
        {
            Debug.Log(playerCtrl.characterInfo.hp);
        }

    }

    public void OnApplicationQuit () {

    }

    public void AsyncLoadScene (string name, Action callBack = null, float time = 0) {
        StartCoroutine (LoadScene (name, callBack, time));
    }
    public IEnumerator LoadScene (string name, Action action, float time) {
        yield return new WaitForSeconds (time);
        UIManager.Instance.loadingView.Show ();
        yield return null;
        AsyncOperation operation = SceneManager.LoadSceneAsync (name);
        operation.allowSceneActivation = false;
        while (operation.progress <= 0.89f) {
            yield return null;
        }
        yield return new WaitForSeconds (4);
        operation.allowSceneActivation = true;
        yield return null;
        if (action != null) action ();
        UIManager.Instance.loadingView.Hide ();
        yield return null;
    }

    public void GameOver () {
        onGameOver.Invoke ();
    }

    public void ReStartGame () {
        UIManager.Instance.combatView.Hide ();
        UIManager.Instance.combatView.ResetView ();
        UIManager.Instance.mainPanel.Show ();
        UIManager.Instance.setBg (true);
        Destroy (PlayerCtrl.gameObject);
        playerCtrl = null;

    }

}

public class DefaultData {
    public static Vector3 playerDefultPos = new Vector3 (-3.58f, -1.34f, 0);
}